<?php


namespace app\api\controller\v2;

use \app\api\controller\Common;
use app\common\service\WXUtils;

class Shareqrcode extends Common
{
    var $modelDb;

    public function _initialize()
    {
        parent::_initialize();
        $this->modelDb = model("ShareQrcode");
    }

    public function qrcode()
    {
        $userid = $this->postData['userid'];
        $articleid = $this->postData['articleid'];
        $page = $this->postData['page'];
        //
        $data = model('ShareQrcode')->where('userid', $userid)->where('articleid', $articleid)->find();
        if ($data) {
            return $this->app_success($data);
        }
        // 1、首先获取access_token
        $wxutils = new WXUtils();
        $access_token = $wxutils->getAccessToken();
        // 2、获取带参数无限个数小程序码
        $scene = $userid . ',' . $articleid;
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $access_token;
        $arr = [
            'scene' => $scene,
            'page' => $page,
            'width' => 280,
            'auto_color' => false,
        ];
        $param_json = json_encode($arr);
        $data = curlPost($url, $param_json);
        // 3、将图片数据data存储到服务器并写入数据库
        $filename = md5('qrcode' . time() . rand(100, 999));
        $filepath = 'upload/articleqrcode/' . $filename . '.png';
        // 存储到服务器
        file_put_contents(ROOT_PATH . $filepath, $data);
        // 写入数据库
        $savedata = [
            'userid' => $userid,
            'articleid' => $articleid,
            'page' => $page,
            'qrcode' => APP_URL . '/' . $filepath,
            'datetime' => SYS_TIME
        ];
        $id = model('ShareQrcode')->save($savedata);
        if ($id) {
            $returndata = model('ShareQrcode')->where('userid', $userid)->where('articleid', $articleid)->find();
            return $this->app_success($returndata);
        } else {
            return $this->app_error();
        }
    }
}